import {
  delUserChannelAction,
  getAllChannelAction,
  getUserChannelAction,
  setChannel_IdAction,
  setUserChannelAction,
} from '@/store/action/channel';
import { useAppSelector } from '@/store/reducer';
import { Popup, Tabs, Toast } from 'antd-mobile';
import { useEffect, useState } from 'react';
import { useDispatch } from 'react-redux';
import Icon from '../Icons';
import styles from './index.module.scss';

// 第三方库
import { differenceBy } from 'lodash';
import { channelListType } from '@/store/reducer/channel';
import history from '@/utils/history';

export default function Channel() {
  // 声明是否显示弹出层的状态
  const [visible, setVisible] = useState(false);
  // 声明是否可以编辑的状态
  const [editAble, setEditAble] = useState(false);
  // 声明一个切换tab栏的状态
  // const [activeId, setActiveId] = useState('0');

  // 修改切换tab栏的状态,把它保存到reducer中
  const { channel_id, userChannelList, allChannelList } = useAppSelector(
    (state) => state.channel
  );

  const dispatch = useDispatch();
  useEffect(() => {
    dispatch(getAllChannelAction());
    dispatch(getUserChannelAction());
  }, [dispatch]);

  // 定义一个剩余频道的计算属性
  // const restList = allChannelList.filter((item) => {
  //   return userChannelList.findIndex((v) => v.id === item.id) === -1;
  // });
  // console.log(restList);

  // 使用lodash计算剩余的频道
  // const restList = differenceBy(allChannelList, userChannelList, 'id');
  const restList = differenceBy(
    allChannelList,
    userChannelList,
    (item) => item.id
  );
  // console.log(restList);

  // 添加频道
  const handleSetChannel = async (item: channelListType) => {
    await dispatch(setUserChannelAction(item));
    Toast.show({ content: '添加成功' });
  };

  // 删除频道
  const handleDelUserChannel = async (id: number) => {
    // 至少保留5个频道
    if (userChannelList.length <= 5)
      return Toast.show({ content: '至少保留5个频道' });

    if (id === 0) return Toast.show({ content: '不能删除推荐频道' });

    await dispatch(delUserChannelAction(id));
    Toast.show({ content: '删除成功' });
  };

  // 关闭弹出层
  const handleClose = () => {
    setVisible(false);
    setEditAble(false);
  };

  return (
    <div className={styles.root}>
      <Tabs
        className="tabs"
        activeKey={String(channel_id)}
        // onChange={(key) => setActiveId(key)}
        onChange={(key) => dispatch(setChannel_IdAction(Number(key)))}
      >
        {userChannelList.map((item) => (
          <Tabs.Tab title={item.name} key={item.id} />
        ))}
      </Tabs>
      <div className="right">
        <Icon type="iconbtn_search" onClick={() => history.push('/search')} />
        <Icon type="iconbtn_channel" onClick={() => setVisible(true)} />
      </div>

      <Popup
        visible={visible}
        position="left"
        bodyClassName={styles.channelPopup}
      >
        {/* 顶部栏：带关闭按钮 */}
        <div className="channel-header">
          <Icon type="iconbtn_channel_close" onClick={handleClose} />
        </div>

        {/* 频道列表 */}
        <div className="channel-content">
          {/* 当前已选择的频道列表 */}
          <div className="channel-item edit">
            <div className="channel-item-header">
              <span className="channel-item-title">我的频道</span>
              <span className="channel-item-title-extra">点击删除频道</span>
              <span
                className="channel-item-edit"
                onClick={() => setEditAble(!editAble)}
              >
                {editAble ? '完成' : '编辑'}
              </span>
            </div>

            <div className="channel-list">
              {userChannelList.map((item) => (
                <span className="channel-list-item" key={item.id}>
                  {item.name}
                  {item.id !== 0 && editAble && (
                    <Icon
                      type="iconbtn_tag_close"
                      onClick={() => handleDelUserChannel(item.id)}
                    />
                  )}
                </span>
              ))}
              {/* <span className="channel-list-item">
                频道1
                <Icon type="iconbtn_tag_close" />
              </span>
              <span className="channel-list-item">
                频道2
                <Icon type="iconbtn_tag_close" />
              </span> */}
            </div>
          </div>

          {/* 推荐的频道列表 */}
          <div className="channel-item">
            <div className="channel-item-header">
              <span className="channel-item-title">频道推荐</span>
              <span className="channel-item-title-extra">点击添加频道</span>
            </div>
            <div className="channel-list">
              {restList.map((item) => (
                <span
                  className="channel-list-item"
                  key={item.id}
                  onClick={() => handleSetChannel(item)}
                >
                  + {item.name}
                </span>
              ))}
              {/* <span className="channel-list-item">+ 推荐1</span>
              <span className="channel-list-item">+ 推荐2</span> */}
            </div>
          </div>
        </div>
      </Popup>
    </div>
  );
}
